<style lang="less">
    @import './org-tree.less';
    @import '../../../styles/common.less';
</style>

<template>
    <Tree :data="orgList" :load-data="loadSubOrg" @on-toggle-expand="resetOrgChildren"
          @on-select-change="selectTreeItem"></Tree>
</template>

<script>
  import _ from 'lodash';
  export default {
    name: 'orgTree',
    data () {
      return {
        orgList: []
      };
    },
    methods: {
      resetOrgChildren (item) {
        if (!item.expand) {
          item.children = [];
        }
      },
      loadSubOrg (item, callback) {
        this.$http.get('/hr/orgs?pid=' + item.id).then(
          function (res) {
            let data = _.map(res.data, o => {
              o.title = o.name;
              if (o.type === 'ORG') {
                o.children = [];
                o.loading = false;
              }

              if (o.type === 'EMPLOYEE') {
                o.title = o.title + ' [' + o.attr.position + ']';
              }

              return o;
            });
            callback(data);
          }).catch((e) => {
          this.$Message.error('加载组织结构失败');
        });
      },
      init () {
        let self = this;
        this.$http.get('/hr/orgs').then(
          function (res) {
            self.orgList = _.map(res.data, o => {
              o.title = o.name;
              o.children = [];
              o.loading = false;
              return o;
            });
          }).catch((e) => {
          this.$Message.error('加载组织结构失败 [ ' + e.message + ' ]');
        });
      },
      selectTreeItem (items) {
        this.$emit('on-select-change', items[0]);
      }
    },
    mounted () {
    }
  };
</script>
